//
//  EFChooseReturnGoodsViewController.m
//  EnjogFood
//
//  Created by guocheng on 2017/5/23.
//  Copyright © 2017年 wf. All rights reserved.
//

#import "EFChooseReturnGoodsViewController.h"
#import "EFReturnGoodsViewItem.h"
#import "EFReturnGoodsViewCell.h"
#import "EFReturnGoodsAllViewItem.h"
#import "EFReturnGoodsAllViewCell.h"
#import "EFReturnGoods.h"

@interface EFChooseReturnGoodsViewController ()<UITableViewDelegate, UITableViewDataSource>

@property(strong,nonatomic)UITableView* tableView;
@property(nonatomic, strong)NSMutableArray *dataArray;
@property(nonatomic, strong)UIButton *okBtn;

@property(assign,nonatomic)NSInteger type;  //0退货 1换货
@property(assign,nonatomic)NSString* orderNo;
@property(strong,nonatomic)EFReturnGoods* returnGoods;


@end

@implementation EFChooseReturnGoodsViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self initData];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        self.title = @"选择退换货商品";
        self.dataArray = [NSMutableArray array];
    }
    return self;
}
-(instancetype)initWithReturnGoosd:(EFReturnGoods *)returnGoods orderNo:(NSString *)orderNo{
    self = [self init];
    if(self){
        self.type = returnGoods.type;
        self.returnGoods = returnGoods;
        self.orderNo = orderNo;
    }
    return self;
}

-(void)initView{
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:self.okBtn];
    [self.view addSubview:self.tableView];
}

-(void)initData{
    
    __weak typeof(self) weakSelf = self;
    [APP_CONTEXT.net getReturnProducts:self.orderNo OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
        if(code == 0){
             if ([info objectForKey:@"list"]) {
                 NSArray *array = [info objectForKey:@"list"];
                 for (NSDictionary *dic in array) {
                     EFReturnGoodsViewItem *item = [EFReturnGoodsViewItem yy_modelWithDictionary:dic];
                     item.totalCount = item.qty;
                     if(weakSelf.returnGoods != nil  && weakSelf.returnGoods.selectArray != nil){
                         for(EFReturnGoodsViewItem* selectItem in weakSelf.returnGoods.selectArray){
                             if([selectItem.id isEqualToString:item.id]){
                                 item.qty -= selectItem.qty;
                             }
                         }
                     }
                     item.restCount = item.qty;
                     if(item.qty > 0 )
                         [weakSelf.dataArray addObject:item];
                 }
                 if(weakSelf.dataArray.count > 0){
                     EFReturnGoodsAllViewItem* item2 = [[EFReturnGoodsAllViewItem alloc] init];
                     item2.totalPrice = @"0";
                     
                     [weakSelf.dataArray addObject:item2];
                     [weakSelf.tableView reloadData];
                 }
                 
             }
        }
    }]; 
}

-(void)onClickOk{
    NSMutableArray* selectArray = [NSMutableArray array];
    for (NSObject *object in self.dataArray) {
        if([object isKindOfClass:[EFReturnGoodsViewItem class]]){
            EFReturnGoodsViewItem* item = (EFReturnGoodsViewItem*)object;
            if(item.selected  && item.qty > 0){
                [selectArray addObject:item];
            }
        }
    }
    if(selectArray.count > 0 ){
        
        EFReturnGoods* retrunGoods = [[EFReturnGoods alloc]initWithType:self.type selectArray:selectArray];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:IC_CHOOSE_GOODS_NOTIFICATION object:retrunGoods];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == self.tableView){
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            [self.dataArray removeObjectAtIndex:indexPath.row];
            // Delete the row from the data source.
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICTableViewItem *item = self.dataArray[indexPath.row];
    return item.viewHeight;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.dataArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICTableViewItem* item = self.dataArray[indexPath.row];
    NSString *identifier = NSStringFromClass(item.viewClass);
    ICTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell = [[item.viewClass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if ([item isKindOfClass:[ICTableViewItem class]]) {
        [cell setObject:item];
    }
    
     if ([item isKindOfClass:[EFReturnGoodsViewItem class]]) {
         ((EFReturnGoodsViewCell *)cell).selectblock = ^(Boolean select){
             ((EFReturnGoodsViewItem*)item).selected = select;
             
             [self modifyData];
         };
         
         ((EFReturnGoodsViewCell *)cell).changeblock = ^(NSInteger count){
             ((EFReturnGoodsViewItem*)item).qty = count;
             
             [self modifyData];
            
         };
     }
    
    if ([item isKindOfClass:[EFReturnGoodsAllViewItem class]]) {
        ((EFReturnGoodsAllViewCell *)cell).selectblock = ^(Boolean select){
            ((EFReturnGoodsAllViewItem*)item).selected = select;

            [self modifyAllData];
        };
    }
    
    return cell;
}

- (UITableView *)tableView{
    if (_tableView == NULL) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kStatusBarHeight - self.okBtn.height)];
        _tableView.delegate = self;
        _tableView.dataSource = self; 
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
    }
    return _tableView;
}

-(UIButton *)okBtn{
    if(_okBtn == NULL){
        _okBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        _okBtn.top = kScreenHeight - kStatusBarHeight -  50;
        _okBtn.backgroundColor = RGBCOLOR(0x69BA45);
        _okBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        _okBtn.titleLabel.textColor = [UIColor whiteColor];
        [_okBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_okBtn addTarget:self action:@selector(onClickOk) forControlEvents:UIControlEventTouchUpInside];
    }
    return _okBtn;
}


-(void)modifyData{
    EFReturnGoodsAllViewItem* all = self.dataArray.lastObject;
    float totalPrice = 0 ;
    for (NSObject *object in self.dataArray) {
        if([object isKindOfClass:[EFReturnGoodsViewItem class]]){
            if(((EFReturnGoodsViewItem*)object).selected){
                totalPrice += ((EFReturnGoodsViewItem*)object).qty*((EFReturnGoodsViewItem*)object).price.floatValue;
            }
        }
    }
    all.totalPrice = @(totalPrice).stringValue;;
    [self.tableView reloadData];
}

-(void)modifyAllData{
    EFReturnGoodsAllViewItem* all = self.dataArray.lastObject;
    float totalPrice = 0 ;
    for (NSObject *object in self.dataArray) {
        if([object isKindOfClass:[EFReturnGoodsViewItem class]]){
            ((EFReturnGoodsViewItem*)object).selected = all.selected;
            if(all.selected){
                totalPrice += ((EFReturnGoodsViewItem*)object).qty*((EFReturnGoodsViewItem*)object).price.floatValue;
            }
        }
    }
    all.totalPrice = @(totalPrice).stringValue;;
    [self.tableView reloadData];
}


@end
